package com.fragments.sendmail;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.Utility.MessageManager;
import com.Utility.Utility;
import com.fragments.BaseFragment;
import com.parser.Error_Report;
import com.senditcertified.mail.R;
import com.senditcertified.mail.widget.dialog.HelpDialog;
import com.soap.call.Http_Soap_Call;

public class VideoFragment extends BaseFragment implements OnClickListener {

	static final int REQUEST_VIDEO_CAPTURE = 1;
	private Activity activity;
	private String videoFileName = "";
	private Uri fileUri;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private View tvHaveAudio;

	@Override
	public void onResume() {
		videoFileName = "";
		super.onResume();
	}
	
	private void dispatchTakeVideoIntent() {
		Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		// create a file to save the video
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO, getActivity().getParent()); 
         
        // set the image file name  
        takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  
         
        // set the video image quality to high
        takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 
		if (takeVideoIntent.resolveActivity(activity.getParent()
				.getPackageManager()) != null) {
			activity.getParent().startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
		}
	}

	/** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type, Activity act){
         
          return Uri.fromFile(getOutputMediaFile(type, act));
    }
 
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type, Activity act){
         
        // Check that the SDCard is mounted
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "MyCameraVideo");
         
         
        // Create the storage directory(MyCameraVideo) if it does not exist
        if (!mediaStorageDir.exists()){
             
            if (! mediaStorageDir.mkdirs()){
                 
                 
                Toast.makeText(act, "Failed to create directory MyCameraVideo.", 
                        Toast.LENGTH_LONG).show();
                 
                return null;
            }
        }
 
         
        // Create a media file name
         
        // For unique file name appending current timeStamp with file name
         
        File mediaFile;
         
        if(type == MEDIA_TYPE_VIDEO) {
             
            // For unique video file name appending current timeStamp with file name
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "video_" + new Date().getTime() + ".mp4");
             
        } else {
            return null;
        }
 
        return mediaFile;
    }
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		tvHaveAudio = getView().findViewById(R.id.tv_have_video);
	}

	@Override
	protected void initComponents() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void addListener() {
		getView().findViewById(R.id.btn_help_record).setOnClickListener(this);
		getView().findViewById(R.id.btn_record).setOnClickListener(this);

	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.sendmail_video_fragment;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_help_record) {
			new HelpDialog(activity.getParent(),
					getString(R.string.send_mail_audio_help_title),
					getString(R.string.send_mail_audio_help_content)).show();
		} else if (id == R.id.btn_record) {
			dispatchTakeVideoIntent();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_VIDEO_CAPTURE
				&& resultCode == Activity.RESULT_OK) {
			File f = new File(fileUri.getPath());
			if (f.length() > 0) {
				videoFileName = f.getName();
				new UploadFileTask().execute(f.getPath(), videoFileName);
			}
		}
	}

	public String getFiles() {
		return videoFileName;
	}

	private class UploadFileTask extends AsyncTask<String, Void, String> {
		private File uploadFile;
		private Error_Report repor = new Error_Report();
		private ProgressDialog dialog;

		@Override
		protected void onCancelled() {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(getActivity().getParent());
			dialog.setMessage(getActivity().getParent().getString(
					R.string.uploading));
			dialog.setCancelable(false);
			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			uploadFile = new File(params[0]);
			try {
				if (uploadFile.exists()) {

					byte b[][] = toByteArray(uploadFile, 262144);

					Http_Soap_Call call = Http_Soap_Call.create_connection("",
							getActivity().getParent());
					if (call != null && b != null) {
						for (int i = 0; i < b.length; i++) {
							call.GetUploadMediResponse(Utility
									.getStringPreference(getActivity()
											.getParent(), "LoginToken", "1"),
									params[1], b[i], i * 262144, repor);
						}

					} else {
						return "No Connection!";
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
				return e.getMessage();
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
				return e.getMessage();
			}

			return "OK";
		}

		@Override
		protected void onPostExecute(String result) {
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}

			if ("OK".equals(result)) {
				MessageManager.showToast(getActivity().getParent(),
						"File uploaded!");
				tvHaveAudio.setVisibility(View.VISIBLE);
			} else {
				videoFileName = "";
				MessageManager.showToast(getActivity().getParent(), result);
			}
		}

	}

	public byte[][] toByteArray(File file, int byteBlockSize)
			throws IOException {
		if (file.exists()) {
			InputStream in = new FileInputStream(file);
			long noOfBlocks = (long) Math.ceil((double) file.length()
					/ (double) byteBlockSize);
			byte[][] result = new byte[(int) noOfBlocks][byteBlockSize];
			int offset = 0;
			for (int i = 0; i < result.length; i++) {
				result[i] = readByteBlock(in, offset, byteBlockSize);
			}
			return result;
		} else
			return null;
	}

	private byte[] readByteBlock(InputStream in, int offset, int noBytes)
			throws IOException {
		byte[] result = new byte[noBytes];
		in.read(result, offset, noBytes);
		return result;
	}
	
	@Override
	public void onDestroyView() {
		if(null != fileUri){
			new File(fileUri.getPath()).delete();
		}
		super.onDestroyView();
	}
}
